package com.rocksdata.mc.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.ctz.commonframe.ui.WebViewActivity;
import com.ctz.commonframe.utils.Logger;
import com.rocksdata.mc.BuildConfig;
import com.rocksdata.mc.business.UserInfoManager;
import com.rocksdata.mc.ui.adapter.WidgetNoticeListAdapter;
import com.rocksdata.mc.R;
import com.rocksdata.mc.business.BusinessInterface;
import com.rocksdata.mc.business.BusinessManager;
import com.rocksdata.mc.entity.AnnouncementInfo;
import com.rocksdata.mc.entity.AppWidgetInfo;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by 陈堂正 on 2017/5/12.
 */

public class AnnouncementWidgetView extends BaseWidgetView {
    private ListView lvNotice;
    private WidgetNoticeListAdapter adapter;
    private List<AnnouncementInfo> announcementInfoList;
    private int announcementIndex;
    private Timer timer;
    private TimerTask task;

    public AnnouncementWidgetView(Context context) {
        super(context);
    }

    public AnnouncementWidgetView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void setupHeadView() {
        ivIcon.setImageResource(R.mipmap.ic_widget_announcement);
        tvName.setText(getResources().getString(R.string.announcement));
        OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(onEnterAppListener != null){
                    onEnterAppListener.onEnterApp(AppWidgetInfo.TYPE_ANNOUNCEMENT);
                }
            }
        };
        layoutHead.setOnClickListener(listener);
        layoutContent.setOnClickListener(listener);
    }

    @Override
    public View getContentView() {
        @SuppressLint("InflateParams")
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.widget_announcement, null);
        lvNotice = contentView.findViewById(R.id.lv_notice);
        lvNotice.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AnnouncementInfo info = (AnnouncementInfo) parent.getItemAtPosition(position);
                if(info != null){
                    try {
                        String url = "file:///android_asset/www/index.html?baseUrl="
                                + URLEncoder.encode(BuildConfig.HOST, "UTF-8")
                                + "&apiToken=" + UserInfoManager.getAccessToken()
                                + "&userType=" + UserInfoManager.getCurrentUserType()
                                + "&userId=" + UserInfoManager.getCurrentUserId()
                                + "#/announcement/" + info.getNoticeCode();
                        Intent intent = new Intent(mContext, WebViewActivity.class);
                        intent.putExtra(WebViewActivity.EXTRA_KEY_URL, url);
                        mContext.startActivity(intent);
                        BusinessInterface.IAnnouncementManager manager = BusinessManager.getAnnouncementManager();
                        if (manager != null)
                            manager.setRead(info.getNoticeCode());
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        return contentView;
    }


    @Override
    public void bindData() {
        BusinessManager.getAnnouncementManager().getAnnouncementListRemote(1, null, null, new BusinessInterface.OnBusinessResultListener() {
            @Override
            public void onBusinessResult(boolean isSuccess, Object object, String message) {
                if(isSuccess){
                    @SuppressWarnings("unchecked")
                    List<AnnouncementInfo> list = (List<AnnouncementInfo>) object;
                    if(announcementInfoList == null)
                        announcementInfoList = new ArrayList<>();
                    else
                        announcementInfoList.clear();
                    if(list != null) {
                        announcementInfoList.addAll(list);
//                        for (AnnouncementInfo info : list) {
//                            if (!info.isRead()) {
//                                announcementInfoList.add(info);
//                            }
//                        }
                    }
                    if(adapter == null) {
                        adapter = new WidgetNoticeListAdapter(mContext, announcementInfoList);
                        lvNotice.setAdapter(adapter);

                    }else{
                        adapter.notifyDataSetChanged();
                    }
                    if(task == null) {
                        task = new TimerTask() {
                            @Override
                            public void run() {
                                if(announcementInfoList.size() > 0) {
                                    if(announcementIndex < announcementInfoList.size() - 1){
                                        int offset = lvNotice.getChildAt(0).getHeight();
                                        lvNotice.smoothScrollBy(offset, 1000);
                                        announcementIndex++;
                                    }else{
                                        lvNotice.smoothScrollToPosition(0);
                                        announcementIndex = 0;
                                    }
                                }
                            }
                        };
                    }
                    if (timer == null) {
                        timer = new Timer();
                        timer.schedule(task, 4000, 4000);
                    }
                }
            }
        });
    }

    @Override
    public void release() {
        if(task != null){
            task.cancel();
        }
        if(timer != null) {
            timer.cancel();
            timer = null;
        }
        announcementIndex = 0;
    }
}
